<script setup>
import { Message, MessageBox } from 'element-ui';
import { find, includes, map, merge } from 'lodash-es';
import { useRequest } from '@/hooks/requestHooks.js';
import { useWatch } from '@/hooks/useWatch.js';
import { searchProjectLists, addMpBasicInfo, removeProject, updateProject } from '@/api/index.js';
import { useConfirmModal } from '@/store/xmgl.js';
import { TableList } from '@/components/MainComponents.js';
import SearchEnterprise from '@/components/EnterpriseInfo/SearchEnterprise.vue';
import MpBasiclnfo from '@/views/xmgl/components/MpBasiclnfo.vue';
import MpContractInfo from '@/views/xmgl/components/MpContractInfo.vue';

const appContainer = ref(null);
const contBoxHeight = ref(null);
const confirmModalStore = useConfirmModal();
const queryParams = ref({
  projectName: '',
  enterpriseCode: '',
  pageNum: 1,
  pageSize: 10,
});
const addBasicInfoParams = ref({
  projectName: '',
  reportCode: '',
  enterpriseCode: '',
});
const open = ref(false);
const openTitle = ref('');
const activeName = ref('jcxx');
const mpciDisabled = ref(true);
const mpbiDisabled = ref(false);
const mpbiReportCode = ref('');
const mpciSubmit = ref(false);
const mpciBuildingCode = ref(null);
const [res, loading, run] = useRequest(searchProjectLists, {
  defaultParams: [{ enterpriseName: '' }],
  manual: true,
});
const [, , addMpBasicInfoRun] = useRequest(addMpBasicInfo, {
  defaultParams: [],
  manual: true,
  onSuccess: data => {
    if (data.code === 200) {
      console.log(data.data, 'data.data=====');
      Message.success(openTitle.value + '成功');
      // activeName.value = 'htxx';
      mpbiDisabled.value = true;
      mpciDisabled.value = false;
      mpbiReportCode.value = data.data.projectCode;
      mpciBuildingCode.value = data.data.buildingLevelOneList;
      handleQuery(queryParams.value);
    }
  },
  onError: rej => {
    if (rej.msg === '所选报告关联区域与其他项目重复不可保存') {
      confirmModalStore.setDisplayCM(true);
    }
    console.log(rej, rej.code, 'rej===');
  },
});
const [, , updateProjectRun] = useRequest(updateProject, {
  defaultParams: [],
  manual: true,
  onSuccess: data => {
    if (data.code === 200) {
      Message.success(openTitle.value + '成功');
      mpciBuildingCode.value = data.data.buildingLevelOneList;
      cancel();
      handleQuery(queryParams.value);
      // activeName.value = 'htxx';
      // mpbiDisabled.value = true;
      // mpciDisabled.value = false;
      // mpbiReportCode.value = data?.rows?.projectCode;
    }
  },
});
const [, , removeProjectRun] = useRequest(removeProject, {
  defaultParams: [],
  manual: true,
  onSuccess: data => {
    loading.value = false;
    handleQuery(queryParams.value);
    Message.success('删除成功');
  },
});
const handleQuery = params => {
  let formdata = new FormData(); //new出来的对象
  Object.keys(params).forEach(key => {
    formdata.append(key, params[key]);
  });
  run(formdata);
};
const checkedChange = val => {
  queryParams.value.enterpriseCode = val?.enterpriseCode;
  handleQuery(queryParams.value);
};
const handleSearch = () => {
  handleQuery(queryParams.value);
};
const resetQuery = () => {
  queryParams.value.projectName = '';
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  handleQuery(queryParams.value);
};
const detailsMp = row => {
  mpciDisabled.value = true;
  mpbiDisabled.value = true;
  open.value = true;
  openTitle.value = '详情';
  mpbiReportCode.value = row.projectCode;
};
const editMp = row => {
  mpbiReportCode.value = row.projectCode;
  confirmModalStore.setOpenTitle('编辑');
  openTitle.value = '编辑';
  mpciDisabled.value = false;
  open.value = true;
};
const deleteMp = row => {
  MessageBox.confirm('是否删除', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      loading.value = true;
      let formdata = new FormData();
      formdata.append('projectCode', row.projectCode);
      removeProjectRun(formdata);
    })
    .catch(() => {});
};
const columObj = ref({
  index: true,
  columnData: [
    {
      text: true,
      prop: 'projectName',
      label: '项目名称',
    },
    {
      text: true,
      prop: 'enterpriseName',
      label: '归属企业',
    },
    {
      text: true,
      prop: 'entrustType',
      label: '托管类型',
    },
    {
      text: true,
      prop: 'entrustStage',
      label: '托管状态',
    },
    {
      text: true,
      prop: 'agreementAmount',
      label: '项目合同总金额（万元）',
    },
    {
      label: '操作',
      operations: [
        {
          type: 'text',
          buttonClick: detailsMp,
          label: '详情',
        },
        {
          type: 'text',
          buttonClick: editMp,
          label: '编辑',
        },
        {
          type: 'text',
          buttonClick: deleteMp,
          label: '删除',
        },
      ],
    },
  ],
});
const getList = e => {
  queryParams.value.pageNum = e.page;
  queryParams.value.pageSize = e.limit;
  handleQuery(queryParams.value);
};
const handleAdd = () => {
  open.value = true;
  openTitle.value = '新增';
};
const selectReport = params => {
  addBasicInfoParams.value = merge(addBasicInfoParams.value, params, {
    enterpriseCode: queryParams.value.enterpriseCode,
  });
};
const mpciUpload = () => {
  mpciSubmit.value = false;
  cancel();
  handleQuery(queryParams.value);
};
const submitForm = () => {
  if (openTitle.value === '详情') {
  } else {
    if (activeName.value === 'jcxx') {
      console.log(addBasicInfoParams.value, 'addBasicInfoParams.value===');
      if (addBasicInfoParams.value.projectName?.length > 0 && addBasicInfoParams.value.reportCode?.length > 0) {
        if (openTitle.value === '新增') addMpBasicInfoRun(addBasicInfoParams.value);
        if (openTitle.value === '编辑')
          updateProjectRun({
            projectCode: mpbiReportCode.value,
            projectName: addBasicInfoParams.value.projectName,
            reportCode: addBasicInfoParams.value.reportCode,
          });
      } else {
        Message.error('请填写项目名称和项目报告');
        return false;
      }
    } else {
      if (mpciDisabled.value) {
        Message.error('请先填写基础信息');
        return false;
      } else {
        mpciSubmit.value = true;
        setTimeout(() => {
          mpciSubmit.value = false;
        }, 1000);
        // cancel();
        // handleQuery(queryParams.value);
      }
    }
  }
};
const cancel = () => {
  open.value = false;
  mpbiDisabled.value = false;
  mpciDisabled.value = true;
  activeName.value = 'jcxx';
  openTitle.value = '';
  mpbiReportCode.value = '';
};
onMounted(() => {
  contBoxHeight.value = appContainer.value.clientHeight - 120 - 122;
});
</script>
<template>
  <div class="app-container u-df-st u-h100" ref="appContainer">
    <div class="architecture-left u-base-fg u-h100 u-br20 u-border-bg">
      <SearchEnterprise @checkedChange="checkedChange" :isDefaultSelect="true" />
    </div>
    <div class="architecture-right u-h100" :v-loading="loading">
      <div class="u-base-fg u-mb20 u-pt20 u-pl20 u-pr20">
        <el-form :model="queryParams" ref="queryForm" :inline="true">
          <el-form-item label="项目名称" prop="projectName">
            <el-input
              class="el-input_search"
              v-model.trim="queryParams.projectName"
              placeholder="请输入"
              clearable
              accordion
              size="small"
              style="width: 372px !important"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleSearch">搜索</el-button>
            <el-button size="small" type="primary" plain @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="contBox" :v-loading="loading">
        <div class="u-df-spb u-mb20">
          <div class="tableTit u-c-3f">托管项目信息列表</div>
          <el-button size="small" type="primary" plain @click="handleAdd">新增托管项目</el-button>
        </div>
        <TableList
          :tableData="res?.rows ?? []"
          :height="contBoxHeight"
          :columObj="columObj"
          :total="res?.total ?? 0"
          :pageObj="queryParams"
          @getList="getList"
        />
      </div>
    </div>
    <el-dialog :visible.sync="open" width="70%" :before-close="cancel" append-to-body>
      <div slot="title" class="dialog-title">
        <span class="tit">
          {{ openTitle }}-
          <span class="u-prim-text">托管项目</span>
        </span>
      </div>
      <div class="u-df-st cursor tabs-box" style="position: relative">
        <div
          class="jcxx-tabs u-sec-text u-df-ct"
          :class="activeName === 'jcxx' ? 'jcxx-ActiveTabs' : ''"
          @click="activeName = 'jcxx'"
        >
          基础信息
        </div>
        <div
          class="htxx-tabs u-sec-text u-df-ct"
          :class="activeName === 'htxx' ? 'htxx-ActiveTabs' : ''"
          @click="activeName = 'htxx'"
        >
          合同信息
        </div>
      </div>
      <div class="xx-box">
        <MpBasiclnfo
          v-show="activeName === 'jcxx'"
          :enterpriseCode="queryParams.enterpriseCode"
          @selectReport="selectReport"
          :cancel="!open"
          :mpbiDisabled="mpbiDisabled"
          :open="open"
          :openTitle="openTitle"
          :mpbiReportCode="mpbiReportCode"
        />
        <MpContractInfo
          v-show="activeName === 'htxx'"
          :enterpriseCode="queryParams.enterpriseCode"
          :cancel="!open"
          :mpciDisabled="mpciDisabled"
          :reportCode="mpbiReportCode"
          :mpciSubmit="mpciSubmit"
          :openTitle="openTitle"
          @mpciUpload="mpciUpload"
          :mpciBuildingCode="mpciBuildingCode"
        />
      </div>

      <div slot="footer" class="dialog-footer" :class="openTitle === '详情' ? 'show-save' : ''">
        <el-button size="small" @click="cancel" type="primary" plain>取 消</el-button>
        <el-button type="primary" size="small" @click="submitForm()">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
@import url(./css/index.scss);
.jcxx-tabs {
  width: 142px;
  height: 40px;
  background: url('../../assets/images/tgxm_jcxx.png') center/100% no-repeat;
  padding-left: -10px;
}
.jcxx-ActiveTabs {
  background: url('../../assets/images/tgxm_jcxx02.png') center/100% no-repeat;
}
.htxx-tabs {
  position: absolute;
  top: 0;
  left: 112px;
  width: 172px;
  height: 40px;
  background: url('../../assets/images/tgxm_htxx02.png') center/100% no-repeat;
}
.htxx-ActiveTabs {
  background: url('../../assets/images/tgxm_htxx.png') center/100% no-repeat;
}
.app-light .tabs-box {
  border-bottom: 1px solid #dcdfe6;
}
.app-dark .tabs-box {
  border-bottom: 1px solid #262f48;
}
.xx-box {
  overflow-y: auto;
  max-height: 580px;
}
.show-save {
  display: none;
}
</style>
